package com.example.zhiran.service.cosservice;

import com.example.zhiran.pojo.front.TempSecret;
import com.example.zhiran.pojo.option.OptionResult;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.TreeMap;

@Service
public class GenerateTempSecret {
    public TempSecret generateSecret(String fileName, String zrId){
        TreeMap<String, Object> config = new TreeMap<>();
        try{
            //设置密钥
            config.put("secretId","AKIDCH9rLbcPxGKAl7E6jBh291g7JGxPbYHn");
            config.put("secretKey","KPGtHQL1SebKo45rOgjX8VfaGgrnUwAA");

//            config.put("host","zhiran-1308915547.cos.ap-guangzhou.myqcloud.com");
            //设置密钥有效时长 2小时
            config.put("durationSeconds", 7200);

            //设置bucket
            config.put("bucket","zhiran-1308915547");
            //设置地区
            config.put("region", "ap-guangzhou");

            //限制允许访问对象
            config.put("allowPrefixes",new String[]{
                    "resource/*",
                    "avatar/*"
            } );

            //
            String[] allowActions = new String[] {
                    //查询对象列表
                    "name/cos:GetBucket",
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分块上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload",
                    //下载对象
                    "name/cos:GetObject",
                    //删除对象
                    "name/cos:DeleteObject"
            };
            config.put("allowActions", allowActions);

            Response response = CosStsClient.getCredential(config);

            return new TempSecret(response.credentials.tmpSecretId,
                    response.credentials.tmpSecretKey,
                    response.credentials.sessionToken);

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return null;
    }
}
